package com.sunyard.inser.web.util;

import java.util.Date;

import com.sunyard.inser.sys.entity.UserInfo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenUtil {
	
	private static final String TOKEN_KEY = "inserToken";
	
	public static String generateToken(UserInfo userInfo) {
		JwtBuilder builder= Jwts.builder().setId(userInfo.getCode())
				.setSubject(userInfo.getName())
				.setIssuedAt(new Date())//用于设置签发时间
				.signWith(SignatureAlgorithm.HS256, TOKEN_KEY);//用于设置签名秘钥
		return builder.compact();
	}
	
	public static UserInfo parseToken(String token) {
		Claims claims =
				Jwts.parser().setSigningKey(TOKEN_KEY).parseClaimsJws(token).getBody();
		UserInfo userInfo = new UserInfo();
		userInfo.setCode(claims.getId());
		userInfo.setName(claims.getSubject());
		return userInfo;
	}
	
	public static void main(String[] args) {
		UserInfo userInfo = new UserInfo();
		userInfo.setCode("ttt");
		userInfo.setName("测试");
//		generateToken(userInfo);
		
		System.out.println(parseToken(generateToken(userInfo)));
	}

}
